package com.wh.wisdomsite.xbox.server;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.ThreadModel;
import com.wh.wisdomsite.xbox.ba.service.IThreadModelService;
import com.wh.wisdomsite.xbox.pojo.ba.ThreadModelIn;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.core.ServiceDispatcher;
import com.wh.wisdomsite.xbox.core.threadpool.JobThreadWeightModel;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;


/**
 * 线程模型管理控制器Controller
 * @Package com.wh.wisdomsite.xbox.server
 * @author 谢泽鹏
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/threadModel")
public class ThreadModelController {

    private static final Log logger = LogFactory.getLog(ThreadModelController.class);

    @Autowired
    private IThreadModelService iThreadModelService;

    @Resource(name = "serviceDispatcher")
    private ServiceDispatcher serviceDispatcher;

    /**
     * 页面跳转
     * @return
     */
    @RequiresPermissions("rules:dataServices_threadModel_page")
    @RequestMapping(value = "index.do",method = RequestMethod.GET)
    public String index(){
        return "/dataServices/threadModel/threadModelList";
    }

    /**
     * 加载数据列表
     * @param response
     * @throws Exception
     */
    @RequiresPermissions("rules:dataServices_threadModel_find")
    @RequestMapping(value = "/threadModelList.do", method = RequestMethod.POST)
    public void threadModelList(HttpServletResponse response,ThreadModelIn in){
        JSONObject json = new JSONObject();
        try {
            logger.info("权重模型列表-->>开始");
            //设置分页
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<ThreadModel> page = new Page<ThreadModel>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置分页条件
            EntityWrapper<ThreadModel> ewThreadModel = new EntityWrapper<ThreadModel>();
            ewThreadModel.setEntity(new ThreadModel());
            ewThreadModel.orderBy("T_CREATE_DATE", false);
            Page<ThreadModel> pageThreadModel = iThreadModelService.selectPage(page, ewThreadModel);
            JSONArray array = new JSONArray();
            if(pageThreadModel.getRecords().size() > 0){
                for(ThreadModel threadModel : pageThreadModel.getRecords()){
                    JSONObject object = new JSONObject(threadModel);
                    object.put("id", threadModel.getId());
                    object.put("createDate", DateTool.format(threadModel.getCreateDate(),"yyyy-MM-dd HH:mm:ss"));
                    object.put("updateDate", DateTool.format(threadModel.getUpdateDate(),"yyyy-MM-dd HH:mm:ss"));
                    array.put(object);
                }
            }
            json.put("total", pageThreadModel.getTotal());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
        } catch (Exception e){
            e.printStackTrace();
            logger.error("权重模型列表-->>Exception" + e.getMessage());
            ResManager.getJsonOut(response).print(json);
        }
        logger.info("权重模型列表-->>结束");
    }

    /**
     * 权重模型详情
     * @param threadModelIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:dataServices_threadModel_view")
    @RequestMapping("threadModelDesc.do")
    public String appSecretDesc(ThreadModelIn threadModelIn, HttpServletRequest request) {
        ThreadModel threadModel = iThreadModelService.selectById(threadModelIn.getId());
        request.setAttribute("threadModel", threadModel);
        request.setAttribute("createDate", DateTool.format(threadModel.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
        request.setAttribute("updateDate", DateTool.format(threadModel.getUpdateDate(), "yyyy-MM-dd HH:mm:ss"));
        return "/dataServices/threadModel/threadModelDesc";
    }

    /**
     * 添加或者修改权重模型
     * @param threadModel
     * @param response
     */
    @RequiresPermissions("rules:dataServices_threadModel_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(ThreadModel threadModel,HttpServletResponse response){
        try {
            if(StringUtils.isNotEmpty(threadModel.getId())){
                logger.info("修改权重模型-->>开始");
                threadModel.setUpdateDate(new Date());
                iThreadModelService.updateById(threadModel);
                logger.info("修改权重模型-->>结束");
                ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("权重模型更新成功"));
            }else {
                logger.info("添加权重模型-->>开始");
                threadModel.setCreateDate(new Date());
                threadModel.setId(UUID.randomUUID().toString().replace("-",""));
                iThreadModelService.insert(threadModel);
                logger.info("添加权重模型-->>结束");
                ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("权重模型添加成功"));
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("操作权重模型-->>Exception" + e.getMessage());
        }
    }


    /**
     * 删除权重模型中选中的列
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:dataServices_threadModel_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String id, HttpServletResponse response){
        try{
            logger.info("删除权重模型-->>开始");
            iThreadModelService.deleteById(id);
            logger.info("删除权重模型-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("权重模型删除成功"));
        } catch (Exception e){
            e.printStackTrace();
            logger.error("删除权重模型-->>Exception" + e.getMessage());
        }
    }

    /**
     * *
     * 重置权重模型
     */
    @RequiresPermissions("rules:dataServices_threadModel_reset")
    @RequestMapping(value = "/resetThreadModel.do", method = RequestMethod.GET)
    public void setThreadModel(HttpServletResponse response) {
        try {
            logger.info("重置权重模型-->>开始");
            EntityWrapper<ThreadModel> ewThreadModel = new EntityWrapper<ThreadModel>();
            ewThreadModel.setEntity(new ThreadModel());
            List<ThreadModel> threadModels = iThreadModelService.selectList(ewThreadModel);
            JobThreadWeightModel[] jobThreadWeightModels = new JobThreadWeightModel[threadModels.size()];
            for (int i = 0; i < threadModels.size(); i++) {
                ThreadModel tm = threadModels.get(i);
                jobThreadWeightModels[i] = new JobThreadWeightModel(tm.getType(), tm.getValue(), tm.getKey());
            }
            serviceDispatcher.getJobDispathcher().rebuildWeightModel(jobThreadWeightModels);
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("重置权重成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("重置权重模型-->>Exception" + e.getMessage());
        }
        logger.info("重置权重模型-->>结束");
    }
}
